<template>
  <div class="warehouse-update-container">
    <el-card class="base-info-card">
      <template #header>
        <span class="card-header-title">编辑仓库信息</span>
      </template>
      <el-form 
        :model="updForm" 
        ref="updFormRef" 
        :rules="rules" 
        label-width="120px"
        v-loading="loading"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="仓库编号">
              <div style="display: flex; align-items: center;">
                <el-input v-model="updForm.wh_code" placeholder="自动获取系统编号" disabled style="margin-right: 35px; flex: 1;" />
                <el-checkbox v-model="updForm.is_default" label="默认仓库" />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="仓库名称" prop="wh_name">
              <el-input v-model="updForm.wh_name" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20"> 
          <el-col :span="12">
            <el-form-item label="仓库容量/m³" prop="wh_capacity">
              <el-input v-model.number="updForm.wh_capacity" placeholder="请输入">
                <template #append>m³</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库管部门" prop="wh_depId">
              <el-select 
                v-model="updForm.wh_depId" 
                placeholder="请选择"
                style="width: 100%"
                @change="handleDepartmentChange"
                clearable
              >
                <el-option 
                  v-for="dept in departmentOptions"
                  :key="dept.department_id"
                  :label="dept.department_name"
                  :value="dept.department_id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="仓库主管" prop="wh_userId">
              <el-select 
                v-model="updForm.wh_userId" 
                placeholder="请选择"
                @change="handleUserChange"
                filterable
                clearable
              >
                <el-option 
                  v-for="user in userOptions"
                  :key="user.user_id"
                  :label="user.user_name"
                  :value="user.user_id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="wh_userPhone">
              <el-input v-model="updForm.wh_userPhone" placeholder="选择主管后自动获取" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="仓库地址" prop="wh_address">
          <el-input v-model="updForm.wh_address" placeholder="请输入" />
        </el-form-item>
        
        
        <el-form-item label="仓库状态" prop="wh_status">
          <el-radio-group v-model="updForm.wh_status">
            <el-radio :label="0">启用</el-radio>
            <el-radio :label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="仓库锁定" prop="is_locked">
          <el-switch v-model="updForm.is_locked" />
        </el-form-item>
        
        <el-form-item label="备注" prop="remark">
          <el-input v-model="updForm.remark" type="textarea" :rows="3" placeholder="请输入" />
        </el-form-item>
        
      </el-form>
    </el-card>

    <div class="action-bar">
      <el-button @click="cancel">关闭</el-button>
      <el-button type="primary" @click="submitForm" :loading="loading">保存</el-button>
    </div>

    <!-- 库位信息部分 -->
    <div class="location-table-container" v-show="updForm.wh_id">
      <el-card class="base-info-card">
        <template #header>
          <span class="card-header-title">库位信息 (共 {{ updForm.wh_slot_num || 0 }} 个库位)</span>
        </template>
        
        <!-- 操作按钮区域 -->
        <div style="text-align: left; margin-bottom: 15px;">  
          <el-button type="success" @click="handleAddSlot">添加</el-button>
          <el-button @click="handleBatchDelete">批量删除</el-button>
          <el-upload
            ref="importUpload"
            style="display: inline-block; margin-left: 10px;"
            :auto-upload="false"
            :on-change="handleFileChange"
            :show-file-list="false"
            accept=".xlsx,.xls"
          >
            <el-button :loading="importLoading">导入</el-button>  
          </el-upload>
          <el-button @click="exportSlots" :disabled="!slotdata.length" style="margin-left: 10px;">导出</el-button>
        </div>
        
        <!-- 无数据提示 -->
        <el-alert
          v-if="!loading && (!slotdata || slotdata.length === 0)"
          title="当前仓库未设置库位"
          type="info"
          show-icon
          :closable="false"
          style="margin-bottom: 15px;"
        />
        
        <!-- 搜索区域 -->
        <div class="search-container">
          <el-form :model="searchParams" class="search-form"> 
            <el-form-item label="仓位:" prop="slot_code" class="form-item">
              <el-input v-model="searchParams.slot_code" placeholder="请输入仓位名称/编号"></el-input>
            </el-form-item>
            
            <el-form-item label="库位名称:" prop="slot_name" class="form-item">
              <el-input v-model="searchParams.slot_name" placeholder="请输入库位名称"></el-input>
            </el-form-item>
            
            <el-form-item label="库位状态:" prop="status" class="form-item">
              <el-select v-model="searchParams.status" placeholder="请选择状态" clearable>
                <el-option label="启用" :value="0"></el-option>
                <el-option label="停用" :value="1"></el-option>
              </el-select>
            </el-form-item>
            
            <el-form-item label="库位主管:" prop="slot_userId" class="form-item">
              <el-select 
                v-model="searchParams.slot_userId" 
                placeholder="请选择库位主管"
                filterable
                clearable
              >
                <el-option 
                  v-for="user in userOptions" 
                  :key="user.user_id" 
                  :label="user.user_name" 
                  :value="user.user_id"
                >
                  <span>{{ user.user_name }}</span>
                  <span style="float: right; color: #8492a6; font-size: 12px">
                    {{ user.user_phone }}
                  </span>
                </el-option>
              </el-select>
            </el-form-item>
         
            <div class="form-actions">
              <el-button @click="resetSearch">重置</el-button>
              <el-button type="success" @click="handleSearch">查询</el-button>
            </div>
          </el-form>
        </div>
        
        <!-- 表格 -->
        <el-table 
          :data="slotdata" 
          style="width: 100%" 
          @selection-change="SelectChange"
          :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
          v-loading="loading"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column type="index" label="序号" width="80"></el-table-column>
          <el-table-column prop="slot_code" label="库位编号" width="135"></el-table-column>
          <el-table-column prop="slot_name" label="库位名称" width="150"></el-table-column>
          <el-table-column prop="slot_capacity" label="库位容量/m³" width="120"></el-table-column>
          <el-table-column prop="slot_userName" label="仓库主管" width="150"></el-table-column>
          <el-table-column prop="slot_status" label="库位状态" width="100" :formatter="formatStatus"></el-table-column>
          <el-table-column prop="remark" label="备注" min-width="150"></el-table-column>
          <el-table-column label="操作" width="150">
            <template #default="scope">
              <el-button type="success" size="small" text @click="showEditDrawer(scope.row)">编辑</el-button>
              <el-button type="danger" size="small" text @click="ShowDelete(scope.row.slot_id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <el-empty 
          v-if="updForm.wh_id && updForm.wh_slot_num > 0 && slotdata.length === 0" 
          description="暂无库位数据" 
          :image-size="100"
          style="padding: 40px 0;"
        />
        
        <!-- 分页 -->
        <el-pagination 
            :page-size="pagination.pageSize" 
            :pager-count="11" 
            layout="prev, pager, next, jumper" 
            :total="pagination.total"
            v-model:current-page="pagination.currentPage"
            @current-change="handlePageChange" 
            style="float:right;margin-top:20px">
        </el-pagination>
      </el-card>
    </div>
    
    <!-- 添加/编辑抽屉 -->
    <el-drawer v-model="drawerVisible" :title="drawerTitle" size="30%">
      <el-form 
        :model="currentSlot" 
        ref="slotFormRef" 
        :rules="slotRules" 
        label-width="120px"
        label-position="left"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="库位编号" prop="slot_code">
              <el-input v-model="currentSlot.slot_code" placeholder="自动获取系统编号" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库位名称" prop="slot_name">
              <el-input v-model="currentSlot.slot_name" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="库位容量/m³" prop="slot_capacity">
              <el-input v-model.number="currentSlot.slot_capacity" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库位主管" prop="slot_userId">
              <el-select 
                v-model="currentSlot.slot_userId" 
                placeholder="请选择"
                filterable
                clearable
              >
                <el-option 
                  v-for="user in userOptions"
                  :key="user.user_id"
                  :label="user.user_name"
                  :value="user.user_id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="库位状态" prop="slot_status">
              <el-radio-group v-model="currentSlot.slot_status">
                <el-radio :label="0">启用</el-radio>
                <el-radio :label="1">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="slot_sort">
              <el-input v-model.number="currentSlot.slot_sort" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="备注" prop="remark">
          <el-input v-model="currentSlot.remark" type="textarea" placeholder="请输入" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div style="flex: auto; text-align: right;">
          <el-button @click="drawerVisible = false">取消</el-button>
          <el-button type="primary" @click="saveSlot">保存</el-button>
        </div>
      </template>
    </el-drawer>

    <!-- 删除确认对话框 -->
    <el-dialog v-model="deleteDialogVisible" width="400" title="确认删除">
      <span>确定删除该库位吗？</span>
      <template #footer>
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmDelete">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import http from '../auth/index'; 
import { ElMessage, ElMessageBox } from 'element-plus';
import * as XLSX from 'xlsx';

export default {
  setup() {
    const route = useRoute();
    const router = useRouter();
    const updFormRef = ref(null);
    const slotFormRef = ref(null);
    const loading = ref(false);
    const id = ref(route.query.id || null);
    const from = ref(route.query.from || 'list');

    // 表单数据
    const updForm = reactive({
      wh_id: '',
      wh_code: '',
      is_default: false,
      wh_name: '',
      wh_capacity: null,
      wh_address: '',
      wh_sort: 0,
      wh_status: 0,
      wh_depId: null,
      wh_depName: '',
      wh_userId: null,
      wh_userName: '',
      wh_userPhone: '',
      is_locked: false,
      remark: '',
      wh_slot_num: 0
    });

    // 部门和用户选项
    const departmentOptions = ref([]);
    const userOptions = ref([]);
    
    // 库位相关数据
    const slotdata = ref([]);
    const selectedRows = ref([]);
    const drawerVisible = ref(false);
    const drawerTitle = ref('添加库位');
    const isEditMode = ref(false);
    const deleteDialogVisible = ref(false);
    const deletingSlotId = ref(null);
    const importLoading = ref(false);
    const importUpload = ref(null);
    
    // 当前操作的库位
    const currentSlot = reactive({
      slot_id: null,
      slot_code: '',
      slot_name: '',
      slot_capacity: null,
      slot_userId: null,
      slot_status: 0,
      slot_sort: null,
      remark: '',
      wh_id: ''
    });

    // 搜索参数
    const searchParams = reactive({
      slot_code: '',
      slot_name: '',
      status: null,
      slot_userId: null
    });

    // 分页配置
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    });

    // 验证规则
    const rules = reactive({
      wh_name: [{ required: true, message: '请输入仓库名称', trigger: 'blur' }],
      wh_capacity: [{ required: true, message: '请输入仓库容量', trigger: 'blur' }],
      wh_depId: [{ required: true, message: '请选择库管部门', trigger: 'change' }],
      wh_address: [{ required: true, message: '请输入仓库地址', trigger: 'blur' }]
    });

    const slotRules = reactive({
      slot_name: [{ required: true, message: '请输入库位名称', trigger: 'blur' }],
      slot_userId: [{ required: true, message: '请选择库位主管', trigger: 'change' }],
      slot_capacity: [{ required: true, message: '请输入库位容量', trigger: 'blur' }],
      slot_sort: [{ required: true, message: '请输入排序号', trigger: 'blur' }]
    });

    // 方法
    const formatStatus = (row) => row.slot_status === 0 ? '启用' : '停用';
    
    const handleDepartmentChange = (depId) => {
      const dept = departmentOptions.value.find(d => d.department_id === depId);
      updForm.wh_depName = dept?.department_name || '';
      updForm.wh_userId = null;
      updForm.wh_userName = '';
      updForm.wh_userPhone = '';
    };

    const handleUserChange = (userId) => {
      if (!userId) {
        updForm.wh_userName = '';
        updForm.wh_userPhone = '';
        return;
      }
      const user = userOptions.value.find(u => u.user_id === userId);
      if (user) {
        updForm.wh_userName = user.user_name;
        updForm.wh_userPhone = user.user_phone || '';
      }
    };

    const fetchDepartments = async () => {
      try {
        const res = await http.get('/Department/GetDepartments');
        departmentOptions.value = res.data.map(item => ({
          department_id: item.department_id,
          department_name: item.department_name
        }));
      } catch (error) {
        console.error('获取部门列表失败:', error);
        ElMessage.error('获取部门列表失败');
      }
    };

    const fetchUsers = async () => {
      try {
        const res = await http.get('/Warehouse/GetAllUsers');
        userOptions.value = res.data.map(item => ({
          user_id: item.user_id,
          user_name: item.user_name,
          user_phone: item.user_phone || ''
        }));
      } catch (error) {
        console.error('获取用户列表失败:', error);
        ElMessage.error('获取用户列表失败');
      }
    };

    const getWarehouseDetails = async () => {
      if (!id.value) {
        ElMessage.warning('缺少仓库ID参数');
        router.go(-1);
        return;
      }
      
      try {
        loading.value = true;
        const res = await http.get(`/Warehouse/GetIdWarehouse?id=${id.value}`);
        if (res.data) {
          Object.assign(updForm, res.data);
          updForm.wh_capacity = Number(res.data.wh_capacity);
          updForm.wh_sort = Number(res.data.wh_sort);
          updForm.wh_status = Number(res.data.wh_status);
          updForm.is_default = res.data.is_default === 1;
          updForm.is_locked = res.data.is_lock === 1;
          updForm.wh_slot_num = res.data.wh_slot_num || 0;
          updForm.wh_id = res.data.wh_id;
          
          await fetchSlots();
        }
      } catch (error) {
        console.error('获取仓库详情失败:', error);
        ElMessage.error('获取仓库详情失败');
        router.go(-1);
      } finally {
        loading.value = false;
      }
    };

    const fetchSlots = async () => {
      if (!updForm.wh_id) return;
      
      try {
        loading.value = true;
        const params = {
          pageSize: pagination.pageSize,
          currentPage: pagination.currentPage,
          warehouseId: updForm.wh_id,
          code: searchParams.slot_code?.trim(),
          name: searchParams.slot_name?.trim(),
          status: searchParams.status,
          userName: searchParams.slot_userId 
            ? userOptions.value.find(u => u.user_id === searchParams.slot_userId)?.user_name 
            : undefined
        };

        const response = await http.get("/Slot/GetSlots", { params });
        
        if (response.data?.code === 200 && response.data.data) {
          const result = response.data.data;
          slotdata.value = (result.list || []).map(slot => ({
            ...slot,
            slot_userName: slot.slot_userName || '未分配'
          }));
          pagination.total = result.rows || 0;
          updForm.wh_slot_num = result.rows || 0;
        }
      } catch (err) {
        console.error('获取库位数据失败:', err);
        ElMessage.error('获取库位数据失败');
        slotdata.value = [];
        pagination.total = 0;
      } finally {
        loading.value = false;
      }
    };

    const handleAddSlot = async () => {
      if (!updForm.wh_id) {
        ElMessage.warning('请先保存仓库基本信息');
        return;
      }
      
      // 生成库位编号
      try {
        const slotCode = await http.get("/CodeRule/GeneratedCode?id=17").then(res => res.data);
        Object.assign(currentSlot, {
          slot_id: null,
          slot_code: slotCode,
          slot_name: '',
          slot_capacity: null,
          slot_userId: null,
          slot_status: 0,
          slot_sort: null,
          remark: '',
          wh_id: updForm.wh_id
        });
        
        drawerTitle.value = '添加库位';
        isEditMode.value = false;
        drawerVisible.value = true;
      } catch (error) {
        console.error('生成库位编号失败:', error);
        ElMessage.error('生成库位编号失败');
      }
    };

    const showEditDrawer = (row) => {
      Object.assign(currentSlot, {
        ...row,
        wh_id: updForm.wh_id
      });
      drawerTitle.value = '编辑库位';
      isEditMode.value = true;
      drawerVisible.value = true;
    };

    const saveSlot = async () => {
      try {
        const valid = await slotFormRef.value.validate();
        if (!valid) return;
        
        // 获取选中的用户信息
        const selectedUser = userOptions.value.find(user => user.user_id === currentSlot.slot_userId);
        
        if (!selectedUser && currentSlot.slot_userId) {
          ElMessage.error('请选择有效的库位主管');
          return;
        }

        // 构建请求数据
        const postData = {
          ...currentSlot,
          slot_userName: selectedUser?.user_name || ''
        };

        const endpoint = isEditMode.value 
          ? '/Slot/UpdateSlot' 
          : '/Slot/AddSlot';
        const httpMethod = isEditMode.value ? 'put' : 'post';

        const res = await http[httpMethod](endpoint, postData);
        
        if (res.data > 0) {
          ElMessage.success(isEditMode.value ? '更新成功' : '添加成功');
          drawerVisible.value = false;
          await fetchSlots();
        } else {
          throw new Error('操作失败');
        }
      } catch (error) {
        console.error('操作出错:', error);
        ElMessage.error(isEditMode.value ? '更新失败' : '添加失败');
      }
    };

    const SelectChange = (selection) => {
      selectedRows.value = selection;
    };

    const ShowDelete = (slotId) => {
      deletingSlotId.value = slotId;
      deleteDialogVisible.value = true;
    };

    const confirmDelete = async () => {
      try {
        console.log('准备删除库位，slot_id:', deletingSlotId.value);
        const res = await http.put('/Slot/DeleteSlot', null, {
          params: { id: deletingSlotId.value }
        });
        console.log('删除接口响应:', res);

        if (res.data > 0) {
          ElMessage.success('删除成功');
          deleteDialogVisible.value = false;
          deletingSlotId.value = null;
          await fetchSlots();
        } else {
          // 这里弹窗显示后端返回的详细信息
          ElMessageBox.alert(
            res.data?.message || '删除失败，后端未返回详细信息',
            '删除失败',
            { type: 'error' }
          );
        }
      } catch (error) {
        console.error('删除库位失败:', error);
        ElMessageBox.alert(
          error.response?.data?.message || error.message || '删除库位失败',
          '删除失败',
          { type: 'error' }
        );
      }
    };

    // 批量删除库位
    const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要删除的库位');
    return;
  }
 
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 个库位吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
 
    // 获取所有选中的ID
    const slotIds = selectedRows.value.map(slot => slot.slot_id);
    
    // 修改为适合后端的批量删除请求方式
    // 方式1：如果后端支持批量删除接口
    const res = await http.post('/Slot/BatchDeleteSlots', { ids: slotIds });
    
    // 或者方式2：逐个删除（不推荐，效率低）
    // const deletePromises = slotIds.map(id => 
    //   http.delete('/Slot/DeleteSlot', { params: { id } })
    // );
    // const results = await Promise.all(deletePromises);
 
    if (res.data.successCount > 0) {
      ElMessage.success(`成功删除 ${res.data.successCount} 个库位`);
      await fetchSlots();
    } else {
      throw new Error(res.data?.message || '批量删除失败');
    }
  } catch (err) {
    if (err !== 'cancel') {
      console.error('批量删除出错:', err);
      ElMessage.error(err.response?.data?.message || '批量删除失败');
    }
  }
};

    // 导入功能
    const handleFileChange = async (file) => {
      if (!file?.raw) return;
      
      const isExcel = /\.(xlsx|xls)$/.test(file.name.toLowerCase());
      if (!isExcel) {
          ElMessage.warning('请上传Excel文件(.xlsx或.xls)');
          return;
      }
  
      importLoading.value = true;
      
      try {
          const formData = new FormData();
          formData.append('file', file.raw);
          formData.append('warehouseId', updForm.wh_id); // 添加仓库ID
  
          const response = await http.post('/Slot/ImportSlots', formData, {
              headers: { 'Content-Type': 'multipart/form-data' },
              timeout: 3600000
          });
  
          if (response.data.successCount > 0) {
              ElMessage.success(`成功导入 ${response.data.successCount} 条数据`);
          }
  
          if (response.data.errors?.length > 0) {
              // 显示前10条错误，避免过多
              const errorMessages = response.data.errors.slice(0, 10).join('\n');
              if (response.data.errors.length > 10) {
                  errorMessages += `\n...还有 ${response.data.errors.length - 10} 条错误未显示`;
              }
              ElMessageBox.alert(errorMessages, '导入错误', {
                  dangerouslyUseHTMLString: true,
                  showConfirmButton: false,
                  showClose: false,
                  customClass: 'error-message-box'
              });
          }
  
          await fetchSlots(); // 刷新数据
      } catch (error) {
          let errorMsg = '导入失败';
          if (error.response) {
              errorMsg = error.response.data?.message || errorMsg;
          } else if (error.message) {
              errorMsg = error.message;
          }
          ElMessage.error(errorMsg);
      } finally {
          importLoading.value = false;
          if (importUpload.value) {
              importUpload.value.clearFiles();
          }
      }
    };

    // 搜索相关
    const resetSearch = () => {
      Object.assign(searchParams, {
        slot_code: '',
        slot_name: '',
        status: null,
        slot_userId: null
      });
      pagination.currentPage = 1;
      fetchSlots();
    };

    const handleSearch = () => {
      pagination.currentPage = 1;
      fetchSlots();
    };

    const handlePageChange = (page) => {
      pagination.currentPage = page;
      fetchSlots();
    };

    const handleSizeChange = (size) => {
      pagination.pageSize = size;
      pagination.currentPage = 1;
      fetchSlots();
    };

    const exportSlots = () => {
      if (slotdata.value.length === 0) {
        ElMessage.warning('没有可导出的数据');
        return;
      }
      
      try {
        const wb = XLSX.utils.book_new();
        const excelData = slotdata.value.map(row => ({
          "仓库名称": updForm.wh_name,
          "库位编号": row.slot_code,
          "库位名称": row.slot_name,
          "库位容量": row.slot_capacity,
          "仓库主管": row.slot_userName,
          "排序": row.slot_sort,
          "状态": row.slot_status === 0 ? '启用' : '停用',
          "备注": row.remark
        }));
        
        const ws = XLSX.utils.json_to_sheet(excelData);
        XLSX.utils.book_append_sheet(wb, ws, "库位信息");
        XLSX.writeFile(wb, `库位信息_${updForm.wh_name}_${new Date().toISOString().slice(0, 10)}.xlsx`);
      } catch (error) {
        console.error('导出失败:', error);
        ElMessage.error('导出失败');
      }
    };

    const submitForm = async () => {
      try {
        const valid = await updFormRef.value.validate();
        if (!valid) return;
        
        const postData = {
          wh_id: updForm.wh_id,
          wh_code: updForm.wh_code,
          is_default: updForm.is_default ? 1 : 0,
          wh_name: updForm.wh_name,
          wh_capacity: Number(updForm.wh_capacity),
          wh_address: updForm.wh_address,
          wh_sort: Number(updForm.wh_sort),
          wh_status: Number(updForm.wh_status),
          wh_depId: Number(updForm.wh_depId),
          wh_depName: updForm.wh_depName,
          wh_userId: updForm.wh_userId ? Number(updForm.wh_userId) : null,
          wh_userName: updForm.wh_userName,
          wh_userPhone: updForm.wh_userPhone,
          is_lock: updForm.is_locked ? 1 : 0,
          update_name: "当前用户",
          update_time: new Date().toISOString(),
          remark: updForm.remark
        };
        
        loading.value = true;
        const res = await http.put('/Warehouse/UpdateWarehouse', postData);
        
        if (res.data?.code === 200) {
          ElMessage.success('更新成功');
          router.go(-1);
        } else {
          throw new Error(res.data?.message || '更新失败');
        }
      } catch (error) {
        console.error('更新失败:', error);
        const msg = error.response?.data?.message || 
                    error.message || 
                    '更新失败，请检查输入数据';
        ElMessage.error(msg);
      } finally {
        loading.value = false;
      }
    };
    

    const cancel = () => {
      router.go(-1);
    };

    // 初始化
    onMounted(async () => {
      await fetchDepartments();
      await fetchUsers();
      if (id.value) {
        await getWarehouseDetails();
      } else {
        updForm.wh_slot_num = 0;
      }
    });

    return {
      updFormRef,
      slotFormRef,
      updForm,
      rules,
      slotRules,
      departmentOptions,
      userOptions,
      slotdata,
      loading,
      drawerVisible,
      drawerTitle,
      currentSlot,
      deleteDialogVisible,
      deletingSlotId,
      selectedRows,
      searchParams,
      pagination,
      importLoading,
      importUpload,
      
      formatStatus,
      handleDepartmentChange,
      handleUserChange,
      fetchSlots,
      handleAddSlot,
      showEditDrawer,
      saveSlot,
      SelectChange,
      ShowDelete,
      confirmDelete,
      handleBatchDelete,
      handleFileChange,
      resetSearch,
      handleSearch,
      handlePageChange,
      handleSizeChange,
      exportSlots,
      submitForm,
      cancel
    };
  }
};
</script>

<style scoped>
.warehouse-update-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.card-header-title {
  font-weight: bold;
  font-size: 16px;
}

.base-info-card {
  width: 80%;
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.location-table-container {
  margin-top: 20px;
}

.search-container {
  width: 100%;
  overflow-x: auto;
}

.search-form {
  display: flex;
  align-items: flex-start;
  flex-wrap: nowrap;
  gap: 15px;
  width: 100%;
}

.form-item {
  flex-shrink: 0;
  margin-bottom: 0;
  width: 230px;
}

.form-actions {
  display: flex;
  gap: 10px;
  flex-shrink: 0;
  padding-top: 5px;
}

@media (max-width: 1200px) {
  .search-form {
    flex-wrap: wrap;
  }
  .form-actions {
    width: 100%;
    justify-content: flex-end;
  }
}

/* 底部操作栏样式 */
.action-bar {
  position: fixed;
  bottom: 0;
  right: 0;
  left: 210px; /* 根据你的侧边栏宽度调整 */
  background: white;
  border-top: 1px solid #e6e6e6;
  padding: 15px 2%; /* 与卡片宽度保持一致 */
  text-align: right;
  z-index: 999;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}
/* 卡片标题左对齐样式 */
.card-header-title {
  display: block;
  text-align: left;
  width: 100%;
  font-weight: bold;
}
</style>